<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="15">
        <el-col>
          <el-button type="primary" @click="addDialogVisibel = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域  row-key="id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}"-->
      <el-table
        :data="rolesList"
        border
        stripe>
        <el-table-column label="" type="expand">
          <!-- eslint-disable-next-line -->
          <template slot-scope="scope">
            <!-- eslint-disable-next-line -->
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 渲染 一级 权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRolesRightById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
              </el-col>
              <!-- 渲染 二级和三级 权限 -->
              <el-col :span="19">
                <!-- 二级 -->
                <!-- eslint-disable-next-line -->
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"  v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRolesRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                  <!-- eslint-disable-next-line -->
                    <el-tag type="warning" v-for="(item3, i3) in item2.children" :key="item3.id" closable @close="removeRolesRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="ID" prop="id"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <!-- eslint-disable-next-line -->
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeRolesById(scope.row.id)">删除</el-button>
            <!-- 分配角色按钮 -->
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="addDialogVisibel" width="50%" @close="addDialogClosed" >
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px" >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisibel = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightsDialogVisibel" width="50%" @close="setRightsDialogClosed" >
      <!-- 内容主体区域 -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisibel = false">取 消</el-button>
        <el-button type="primary" @click="allRights">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 控制 添加对话框的显示与隐藏
      addDialogVisibel: false,
      // 添加用户的表单数据对象
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 区分 add 和 edit 的标识,1:默认为添加  2:编辑
      iFlag: 1,
      dialogTitle: '添加角色',
      // 控制分配权限的显示隐藏
      setRightsDialogVisibel: false,
      // 权限列表
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的数据
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      // console.log(res.data)
    },
    // 关闭弹框
    addDialogClosed() {
      // 把获取的表单值 初始化(清空)
      this.$refs.addFormRef.resetFields()
    },
    // 确定添加角色
    addRoles() {
      // 获取表单值
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        if (this.iFlag === 1) {
          // add 发送数据到后台
          const { data: res } = await this.$http.post('roles', this.addForm)
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
        } else {
          // edit 发送数据到后台
          const { data: res } = await this.$http.put(
            'roles/' + this.addForm.roleId,
            {
              roleName: this.addForm.roleName,
              roleDesc: this.addForm.roleDesc
            }
          )
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
        }
        this.iFlag = 1
        this.dialogTitle = '添加角色'
        this.addDialogVisibel = false
        this.getRolesList()
      })
    },
    // 编辑 - 点击编辑按钮 根据 ID 查询角色
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.addForm = res.data
      this.addDialogVisibel = true
      this.iFlag = 2
      this.dialogTitle = '编辑角色'
    },
    // 删除 - 根据ID删除数据
    async removeRolesById(id) {
      // 弹框询问
      const confirmRes = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      // 点击确认按钮 -> 返回值为字符串 confirm
      // console.log(confirmRes); // confirm

      // 点击取消按钮 -> 返回值为字符串 cancel
      // console.log(confirmRes); // cancel

      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },
    // 删除指定角色的权限
    async removeRolesRightById(role, rightId) {
      // 弹框询问
      const confirmRes = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      // 点击确认按钮 -> 返回值为字符串 confirm
      // console.log(confirmRes); // confirm

      // 点击取消按钮 -> 返回值为字符串 cancel
      // console.log(confirmRes); // cancel

      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      // this.getRolesList()
      role.children = res.data
    },
    // 分配权限按钮 弹出框
    async showSetRightDialog(role) {
      // console.log('id:' + this.defKeys)
      this.roleId = role.id
      // 获取权限列表 - 树形组件
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.rightsList = res.data
      // 调用 递归函数 getLeafKeys ,获取三级节点的id
      this.getLeafKeys(role, this.defKeys)
      this.setRightsDialogVisibel = true
    },
    // 通过递归的形式，获取角色下的所有第三级权限id，并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前 node 界定不包含 children 属性，则是第三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      // 则重新调用
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听 对话框 关闭事件
    setRightsDialogClosed() {
      this.defKeys = []
    },
    // 确认选中节点并发送到后台
    async allRights() {
      // ... :展开运算符
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.setRightsDialogVisibel = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
</style>
